<script setup>
  import { inject, ref } from 'vue'
  import Button from '@/components/Button.vue'
  import { PROVIDE_KEY } from '../consts'
  import FileList from '../list/FileList.vue'
  import Icon from '@/components/Icon.vue'

  import TaskNode from './TaskNode.vue'

  const props = defineProps({
    node: { type: Object, required: true },
    open: { type: Boolean, default: true },
    taskId: { type: Number, required: false },
  })

  const { onFileAdd } = inject(PROVIDE_KEY)

  const visible = ref(props.open)
  const toggleVisible = () => {
    visible.value = !visible.value
  }
</script>
<template>
  <tbody class="collapse_title">
    <tr>
      <td class="empty" colspan="7"></td>
    </tr>
    <tr class="row_recap">
      <td class="col_text" colspan="6">
        <h4>
          <a
            class="collapse_button"
            href="#"
            @click="() => toggleVisible()"
            :aria-expanded="visible"
          >
            <Icon css="arrow" name="chevron-down"></Icon>
            Affaire : {{ node.name }}
          </a>
        </h4>
      </td>
      <td class="col_actions width_four">
        <Button
          :show-label="true"
          class="btn-primary"
          label="Fichier"
          icon="plus"
          title="Ajouter un fichier au devis"
          @click="() => onFileAdd(node)"
        />
      </td>
    </tr>
  </tbody>
  <tbody class="collapse_content" v-if="visible">
    <FileList :node="node" :key="node.id" :level="1" />
  </tbody>
  <TaskNode
    v-if="visible"
    :node="estimation"
    :level="2"
    v-for="estimation in node.estimations"
    :open="!taskId || estimation.id === taskId"
    :key="estimation.id"
  />
  <TaskNode
    v-if="visible"
    :node="invoice"
    :level="2"
    v-for="invoice in node.invoices"
    :open="!taskId || invoice.id === taskId"
    :key="invoice.id"
  />
</template>
